package com.bst.bsj.bops.web.controller;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.bst.bsj.base.controller.WebBaseController;
import com.bst.bsj.bops.BopsConstants;
import com.bst.bsj.portal.yun.service.ImageYunService;
import com.homewaimai.framework.web.request.session.LoginUser;

@Scope("prototype")
@Controller
@RequestMapping(value = "/sys/image")
public class UploadImageController extends WebBaseController {

	@Autowired
	private ImageYunService imageYunService;

	@RequestMapping(value = "/view", method = RequestMethod.GET)
	public ModelAndView view(HttpServletRequest request) {

		ModelAndView mav = new ModelAndView("content/imageUpload");
		mav.addAllObjects(getBopsParams(request));
		return mav;
	}

	@RequestMapping(value = "/upload")
	public void doupload(String type, HttpServletRequest request,
			HttpServletResponse response) {

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件：
		MultipartFile upload = multipartRequest.getFile("upload");

		if (upload == null) {
			upload = multipartRequest.getFile("file");
		}

		boolean bl = true;
		String message = "";
		try {

			response.setContentType("text/html;charset=utf-8");

			InputStream fis = upload.getInputStream();

			SimpleDateFormat dataFormat = new SimpleDateFormat(
					"yyyyMMddHHmmssSSSS");
			Date currentTime = new Date();
			String postName = ".jpg";

			String subcontextPath = dataFormat.format(currentTime) + postName;

			LoginUser loginUser = getLoginUser(request);
			String subImgDir = loginUser.getMemberId();

			String contextPath = subImgDir + File.separator + subcontextPath;

			byte bt[] = new byte[fis.available()];
			fis.read(bt);

			if (!imageYunService.writeFile(BopsConstants.IMG_MANAGER_PRE_ROOT_URL + contextPath, bt,
					true)) {

				logger.error("upYunService error"
						+ imageYunService.getOutputDir());
				bl = false;

			}

			fis.close();
			message =BopsConstants.IMG_MANAGER_PRE_URL + contextPath;

		} catch (Exception e) {
			logger.error("FileUploadAction error", e);
			bl = false;
		}

		if ("json".equals(type)) {

			message = bl ? "{\"code\":\"200\",\"data\":\"" + message + "\"}"
					: "{\"code\":\"201\",\"data\":\"error\"}";

		}

		// output
		write(response, message);

	}

}
